<template>
  <div v-loading="loading" class="customer_service_assign" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addRule"> 新建分配规则 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length === 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="name"
          placeholder="名称搜索"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <!-- 列表表格 -->
    <div class="table_container">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        height="100%"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
          :align="'center'"
          fixed="left"
        />
        <el-table-column show-overflow-tooltip prop="name" label="规则名称" min-width="200" />
        <el-table-column show-overflow-tooltip prop="moduleName" label="模块名称" width="250" />
        <el-table-column show-overflow-tooltip prop="condition" label="规则条件" width="150" />
        <el-table-column show-overflow-tooltip prop="type" label="分配方式" width="80">
          <template #default="scope">
            <span v-if="scope.row.type == 1">平均分配</span>
            <span v-if="scope.row.type == 2">随机分配</span>
            <span v-if="scope.row.type == 3">熟客优先</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="empType" label="人员类型" width="80">
          <template #default="scope">
            <span v-if="scope.row.empType == 1">客服</span>
            <span v-if="scope.row.empType == 2">客服组</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="emp" label="分配人员" width="250" />
        <el-table-column show-overflow-tooltip prop="weight" label="优先级" width="70" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="150" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="150" />
        <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" fixed="right">
          <template #default="scope">
            <h-space>
              <HLink @click="editRule(scope.row.id)">编辑</HLink>
              <h-link type="error" @click="handleCustomerServiceAssignRule(scope.row)">删除</h-link>
            </h-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="pagination">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList(false)"
      />
    </div>

    <!-- 添加/编辑  规则弹窗 -->
    <h-drawer
      v-model="addDialog"
      :width="800"
      unit="px"
      :title="dialogTitle"
      :loading="dialogLoading"
    >
      <el-form
        ref="formRef"
        label-position="top"
        inline-message
        class="modal_form_content"
        :rules="rules"
        :model="form"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model.trim="form.name" clearable placeholder="请输入名称" />
        </el-form-item>
        <div class="role_container">
          <div class="title">
            <div class="text">需满足以下所有条件，自动分配规则才会生效</div>
            <h-link @click="addCondition">添加</h-link>
          </div>

          <div class="role_list">
            <template v-for="(item, i) in form.conditionVos" :key="i">
              <el-form-item class="role_panel">
                <template #label>
                  <div class="role_panel_label">
                    <span class="title">规则{{ ['一', '二', '三', '四'][i] }}</span>
                    <h-link type="error" @click="deleteCondition(i, item.id)">删除</h-link>
                  </div>
                </template>
                <div class="role_panel_content">
                  <el-form-item
                    class="mb10"
                    label="规则条件"
                    :prop="`conditionVos[${i}][type]`"
                    :rules="rules.type"
                  >
                    <el-select
                      v-model="item.type"
                      class="width-select"
                      filterable
                      clearable
                      placeholder="请选择条件"
                    >
                      <el-option label="品牌" :value="1" />
                      <el-option label="设备分类" :value="2" />
                      <el-option label="公司区域" :value="3" />
                      <!-- <el-option label="工单模块" :value="4" /> -->
                    </el-select>
                  </el-form-item>
                  <el-form-item label="规则内容">
                    <el-select v-if="!item.type" class="width-select" placeholder="请先选择条件">
                    </el-select>
                    <el-select
                      v-if="item.type === 1"
                      v-model="item.conditionChildVos[0].valId"
                      class="width-select"
                      placeholder="请选择品牌"
                      filterable
                      clearable
                      remote
                      reserve-keyword
                      remote-show-suffix
                      :loading="brandLoad"
                      :remote-method="searchBrandSelect"
                    >
                      <el-option
                        v-for="item in brandOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                    <el-select
                      v-if="item.type === 2"
                      v-model="item.conditionChildVos[0].valId"
                      class="width-select"
                      placeholder="请选择分类"
                      filterable
                      clearable
                      remote
                      reserve-keyword
                      remote-show-suffix
                      :loading="typeLoad"
                      :remote-method="searchTypeSelect"
                    >
                      <el-option
                        v-for="item in typeOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                    <SingleAddress
                      v-if="item.type === 3"
                      ref="addrsDom"
                      :address="addrsData"
                      @change="handleAddressUpdate"
                    />
                    <el-select
                      v-if="item.type === 4"
                      v-model="item.conditionChildVos[0].valId"
                      class="width-select"
                      placeholder="请选择工单模块"
                      filterable
                      clearable
                      remote
                      reserve-keyword
                      remote-show-suffix
                      :loading="moduleLoad"
                      :remote-method="searchModuleSelect"
                    >
                      <el-option
                        v-for="item in moduleOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </div>
              </el-form-item>
            </template>
          </div>
        </div>
        <div class="radio_group">
          <div class="tips">满足以上条件，则执行以下分配策略</div>
          <div class="form_item_container">
            <el-form-item label="分配方式" class="same_line">
              <el-radio-group v-model="form.type">
                <el-radio :value="1" size="small">平均分配</el-radio>
                <el-radio :value="2" size="small">随机分配</el-radio>
                <el-radio :value="3" size="small">熟客优先</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="人员类型" class="same_line">
              <el-radio-group v-model="form.empType" @change="typeChange">
                <el-radio :value="1" size="small">客服</el-radio>
                <el-radio :value="2" size="small">客服组</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
        <el-form-item v-if="form.empType == 2" label="客服组人员" class="form-item">
          <el-select
            v-model="form.serviceIds"
            class="item-select"
            placeholder="请选择客服组人员"
            multiple
            collapse-tags
            collapse-tags-tooltip
            filterable
            clearable
            remote
            reserve-keyword
            remote-show-suffix
            :loading="customLoad"
            :remote-method="searchTeamSelect"
          >
            <el-option
              v-for="item in teamOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.empType == 1" label="客服人员" class="form-item">
          <el-select
            v-model="form.serviceIds"
            class="item-select"
            placeholder="请选择客服人员"
            multiple
            collapse-tags
            collapse-tags-tooltip
            filterable
            clearable
            remote
            reserve-keyword
            remote-show-suffix
            :max-collapse-tags="5"
            :loading="customLoad"
            :remote-method="searchCustomSelect"
          >
            <el-option
              v-for="item in customOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-input v-model.trim="form.weight" clearable placeholder="不填写则系统默认排序" />
        </el-form-item>
        <el-form-item label="规则状态" class="same_line">
          <el-radio-group v-model="form.status">
            <el-radio :value="false" size="small">启用</el-radio>
            <el-radio :value="true" size="small">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <HPlainBgButton
          v-show="dialogTitle === '编辑规则'"
          is-modal
          type="error"
          @click="changeAll(4)"
          >删除</HPlainBgButton
        >
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="addDialog = false">取消</HButton>
      </template>
    </h-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, watch } from 'vue'
  import { Search, Warning, Delete, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, TableInstance } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import { workModulePageSelect, workTeamPageSelect } from '@/api/order'
  import {
    clientGetList,
    clientSave,
    clientDisable,
    clientDelete,
    clientGetDetail,
  } from '@/api/basic'
  import { empPageSelecct } from '@/api/organize'
  import { brandPageSelect, typePageSelect } from '@/api/goodsInfo'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { CustomerServiceAssignRule } from './types'

  const handleCustomerServiceAssignRule = (
    customerServiceAssignRule: CustomerServiceAssignRule,
  ) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(customerServiceAssignRule, true)
      changeAll(3)
    }
  }

  const name = ref('') // 名称
  const tableData = ref([]) // 列表数据
  const tableDom = ref<TableInstance | null>(null) // 列表dom
  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目
  const loading = ref(false)
  const addDialog = ref(false)
  const dialogTitle = ref('')
  const dialogLoading = ref(false)
  const formRef = ref<FormInstance>() // 表单元素

  // 表单数据
  const form = reactive({
    conditionVos: [
      {
        id: null,
        conditionChildVos: [
          {
            area: '',
            city: '',
            province: '',
            town: '',
            valId: '',
          },
        ],
        type: null,
      },
    ],
    delConditionIds: [],
    empType: 1,
    id: null,
    name: '',
    serviceIds: [],
    status: false,
    type: 1,
    weight: 0,
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择规则条件', trigger: 'blur' }],
  })

  // 工单模块下拉相关
  const moduleOptions = ref([])
  const moduleLoad = ref(false)
  const moduleVal = ref('')

  // 客服 客服组下拉相关
  const customOptions = ref([])
  const teamOptions = ref([])
  const customLoad = ref(false)
  const customVal = ref('')
  const teamVal = ref('')

  // 设备品牌下拉相关
  const brandOptions = ref([])
  const brandLoad = ref(false)
  const brandVal = ref('')

  // 设备分类下拉相关
  const typeOptions = ref([])
  const typeLoad = ref(false)
  const typeVal = ref('')

  const addrsDom = ref()
  const addrsData = ref()

  // 列表序号
  const indexMethod = (index: number) => {
    return index + 1
  }

  // 获取工单模块下拉
  const getModuleOptions = (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    workModulePageSelect(data).then((res) => {
      moduleOptions.value = res.data.data.rows
    })
  }

  // 搜索工单模块下拉
  const searchModuleSelect = (query) => {
    moduleVal.value = query
    if (query) {
      moduleLoad.value = true
      setTimeout(async () => {
        moduleLoad.value = false
      }, 1000)
    }
  }

  // 获取设备品牌下拉
  const getBrandOptions = (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    brandPageSelect(data).then((res) => {
      brandOptions.value = res.data.data.rows
    })
  }

  // 搜索设备品牌下拉
  const searchBrandSelect = (query) => {
    brandVal.value = query
    if (query) {
      brandLoad.value = true
      setTimeout(async () => {
        brandLoad.value = false
      }, 1000)
    }
  }

  // 获取设备分类下拉
  const getTypeOptions = (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    typePageSelect(data).then((res) => {
      typeOptions.value = res.data.data.rows
    })
  }

  // 搜索设备分类下拉
  const searchTypeSelect = (query) => {
    typeVal.value = query
    if (query) {
      typeLoad.value = true
      setTimeout(async () => {
        typeLoad.value = false
      }, 1000)
    }
  }

  // 获取客服人员下拉
  const getCustomOptions = (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    empPageSelecct(data).then((res) => {
      customOptions.value = res.data.data.rows
    })
  }

  // 搜索客服人员下拉
  const searchCustomSelect = (query) => {
    customVal.value = query
    if (query) {
      customLoad.value = true
      setTimeout(async () => {
        customLoad.value = false
      }, 1000)
    }
  }

  // 获取客服组人员下拉
  const getTeamOptions = (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    workTeamPageSelect(data).then((res) => {
      teamOptions.value = res.data.data.rows
    })
  }

  // 搜索客服组人员下拉
  const searchTeamSelect = (query) => {
    teamVal.value = query
    if (query) {
      customLoad.value = true
      setTimeout(async () => {
        customLoad.value = false
      }, 1000)
    }
  }

  // 监听下拉数据变化时是否进行搜索
  watch(
    () => moduleVal.value,
    (newVal) => {
      if (newVal != '') {
        getModuleOptions(newVal)
      } else {
        getModuleOptions('')
      }
    },
  )
  watch(
    () => customVal.value,
    (newVal) => {
      if (newVal != '') {
        getCustomOptions(newVal)
      } else {
        getCustomOptions('')
      }
    },
  )
  watch(
    () => teamVal.value,
    (newVal) => {
      if (newVal != '') {
        getTeamOptions(newVal)
      } else {
        getTeamOptions('')
      }
    },
  )
  watch(
    () => brandVal.value,
    (newVal) => {
      if (newVal != '') {
        getBrandOptions(newVal)
      } else {
        getBrandOptions('')
      }
    },
  )
  watch(
    () => typeVal.value,
    (newVal) => {
      if (newVal != '') {
        getTypeOptions(newVal)
      } else {
        getTypeOptions('')
      }
    },
  )

  // 人员类型变化时
  const typeChange = () => {
    form.serviceIds = []
  }

  // 添加条件
  const addCondition = () => {
    if (form.conditionVos.length == 4) {
      ElMessage({
        message: '最多添加4个条件！',
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    form.conditionVos.push({
      id: null,
      conditionChildVos: [
        {
          area: '',
          city: '',
          province: '',
          town: '',
          valId: '',
        },
      ],
      type: null,
    })
  }

  // 删除条件
  const deleteCondition = (i, id) => {
    if (form.conditionVos.length == 1) {
      ElMessage({
        message: '至于保留1个条件！',
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    form.conditionVos.splice(i, 1)
    if (id) {
      form.delConditionIds.push(id)
    }
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取分页数据
  const getPageData = (val) => {
    if (val) pagination.value.setPage()
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async (val = true) => {
    loading.value = true
    await clientGetList(getPageData(val)).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  defineExpose({ getList })

  // 添加规则
  const addRule = () => {
    dialogTitle.value = '添加规则'
    addDialog.value = true
    getModuleOptions('')
    getBrandOptions('')
    getTypeOptions('')
    getCustomOptions('')
    getTeamOptions('')
    form.conditionVos = [
      {
        id: null,
        conditionChildVos: [
          {
            area: '',
            city: '',
            province: '',
            town: '',
            valId: '',
          },
        ],
        type: null,
      },
    ]
    form.delConditionIds = []
    form.empType = 1
    form.id = null
    form.name = ''
    form.serviceIds = []
    form.status = false
    form.type = 1
    form.weight = 0
  }

  // 编辑规则
  const editRule = async (id) => {
    dialogTitle.value = '编辑规则'
    addDialog.value = true
    dialogLoading.value = true
    getModuleOptions('')
    getBrandOptions('')
    getTypeOptions('')
    getCustomOptions('')
    getTeamOptions('')
    form.delConditionIds = []
    await clientGetDetail(id).then((res) => {
      form.conditionVos = res.data.data.row.conditionVos
      form.conditionVos.forEach((item) => {
        if (item.conditionChildVos[0].valId == '0') {
          item.conditionChildVos[0].valId = ''
        }
      })
      res.data.data.row.conditionVos.forEach((item) => {
        if (item.type == 3) {
          addrsData.value = {
            province: item.conditionChildVos[0].province,
            city: item.conditionChildVos[0].city,
            area: item.conditionChildVos[0].area,
            town: item.conditionChildVos[0].town,
          }
        }
      })
      form.empType = res.data.data.row.empType
      form.id = res.data.data.row.id
      form.name = res.data.data.row.name
      form.serviceIds = res.data.data.row.serviceIds
      form.status = res.data.data.row.status
      form.type = res.data.data.row.type
      form.weight = res.data.data.row.weight
    })
    dialogLoading.value = false
  }

  // 保存方法
  const saveDataMethod = (method, data) => {
    dialogLoading.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        addDialog.value = false
        dialogLoading.value = false
        getList()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'warning',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        dialogLoading.value = false
        return
      }
    })
  }

  // 地址
  const address = ref({
    province: '',
    area: '',
    city: '',
    town: '',
  })

  // 地址更新事件
  const handleAddressUpdate = (addr: {
    province: string
    area: string
    city: string
    town: string
  }) => {
    address.value.province = addr.province
    address.value.area = addr.area
    address.value.city = addr.city
    address.value.town = addr.town
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        if (addrsDom.value) {
          form.conditionVos.forEach((item) => {
            if (item.type == 3) {
              item.conditionChildVos[0].area = address.value.area
              item.conditionChildVos[0].city = address.value.city
              item.conditionChildVos[0].province = address.value.province
              item.conditionChildVos[0].town = address.value.town
            } else {
              item.conditionChildVos[0].area = ''
              item.conditionChildVos[0].city = ''
              item.conditionChildVos[0].province = ''
              item.conditionChildVos[0].town = ''
            }
          })
        }
        // 判断条件是否重复
        let isRepeat
        const newArr = form.conditionVos.map((item) => item.type)
        isRepeat = newArr.some((x, index, arr) => arr.findIndex((y) => y == x) != index)
        if (isRepeat) {
          ElMessage({
            message: '规则条件重复',
            type: 'warning',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          return
        }
        saveDataMethod(clientSave, form)
      }
    })
  }

  // 修改状态的方法
  const chnageMethod = (arr, type, method, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的规则`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的规则?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n) => {
    switch (n) {
      case 1:
        chnageMethod(selecttion.value, '启用', clientDisable, false, '')
        break
      case 2:
        chnageMethod(selecttion.value, '禁用', clientDisable, true, '')
        break
      case 3:
        chnageMethod(selecttion.value, '删除', clientDelete, 3, '')
        break
      case 4:
        chnageMethod([form.id], '删除', clientDelete, 3, 1)
        break
    }
  }
</script>

<style scoped lang="scss">
  @import '../../index.scss';
  @import './CustomerRules.scss';
</style>
